package jxd.myDwr;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.directwebremoting.extend.Handler;
import org.directwebremoting.extend.Remoter;
import org.directwebremoting.util.LocalUtil;

public class InterfaceHandler
  implements Handler
{
  protected Remoter remoter = null;
  protected String interfaceHandlerUrl;

  public void handle(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    String scriptName = request.getPathInfo();
    scriptName = LocalUtil.replace(scriptName, this.interfaceHandlerUrl, "");
    scriptName = LocalUtil.replace(scriptName, ".js", "");
    if (!LocalUtil.isJavaIdentifier(scriptName))
    {
      throw new SecurityException("Script names may only contain Java Identifiers");
    }

    String path = request.getContextPath() + request.getServletPath();

    String script = this.remoter.generateInterfaceScript(scriptName, path);

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.print(script);
  }

  public void setRemoter(Remoter remoter)
  {
    this.remoter = remoter;
  }

  public void setInterfaceHandlerUrl(String interfaceHandlerUrl)
  {
    this.interfaceHandlerUrl = interfaceHandlerUrl;
  }
}